package br.edu.ifrn.view;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import br.edu.ifrn.controller.UsuarioEJBLocal;
import br.edu.ifrn.model.Usuario;

@ManagedBean
@ViewScoped
public class LoginMBean {
	private String login;
	private String senha;
	
	@EJB
	UsuarioEJBLocal usuarioEJB;
	
	public String getLogin() {
		return login;
	}
	
	public void setLogin(String login) {
		this.login = login;
	}
	
	public String getSenha() {
		return senha;
	}
	
	public void setSenha(String senha) {
		this.senha = senha;
	}
	
	public String actionLogar() {
		Usuario usuario = usuarioEJB.logar(login, senha);
		
		if (usuario != null) {
		    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		    session.setAttribute("usuario", usuario);
		    
			return "/busca/busca.xhtml";
		} else {
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Login ou Senha incorreto.", null));
		}
		
		return "";
	}
	
	public String actionLogout() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		session.invalidate();
		
		return "../login.xhtml";
	}
}
